import React, { useState, useEffect, useRef } from 'react';
import './Character.css';

const Character = ({ onCollectPet, availablePets, mapWidth, mapHeight }) => {
  const intervalRef = useRef(null);
  // 角色位置状态
  const [position, setPosition] = useState({ x: Math.min(mapWidth / 2 - 30, mapWidth - 60), y: Math.min(mapHeight / 2 - 30, mapHeight - 60) });
  // 移动方向状态
  const [direction, setDirection] = useState('down');
  // 是否正在移动
  const [isMoving, setIsMoving] = useState(false);
  // 角色引用，用于碰撞检测
  const characterRef = useRef(null);

  // 处理键盘按下事件
  useEffect(() => {
    const handleKeyDown = (e) => {
      // 首先根据按键更新方向
      let newDirection = direction;
      let shouldMove = true;

      switch(e.key) {
        case 'w':
        case 'W':
          newDirection = 'up';
          break;
        case 's':
        case 'S':
          newDirection = 'down';
          break;
        case 'a':
        case 'A':
          newDirection = 'left';
          break;
        case 'd':
        case 'D':
          newDirection = 'right';
          break;
        default:
          shouldMove = false;
          return;
      }
      
      // 更新方向状态
      setDirection(newDirection);
      
      if (shouldMove) {
        setIsMoving(true);
        
        // 移动角色
        setPosition(prev => {
          let newX = prev.x;
          let newY = prev.y;
          const moveStep = 8;
          const characterWidth = 60; // 角色宽度
          const characterHeight = 60; // 角色高度
          
          const margin = 0; // 移除边界安全距离，确保角色可以贴边移动
          switch(newDirection) {
            case 'up':
              newY = Math.max(0, Math.min(newY - moveStep, mapHeight - characterHeight));
              break;
            case 'down':
              newY = Math.max(0, Math.min(newY + moveStep, mapHeight - characterHeight));
              break;
            case 'left':
              newX = Math.max(0, Math.min(newX - moveStep, mapWidth - characterWidth));
              break;
            case 'right':
              newX = Math.max(0, Math.min(newX + moveStep, mapWidth - characterWidth));
              break;
          }
          return { x: newX, y: newY };
        });
      }
      
      // 阻止默认行为，防止页面滚动
      e.preventDefault();
    };

    // 处理键盘松开事件
    const handleKeyUp = (e) => {
      if (['w', 'W', 'a', 'A', 's', 'S', 'd', 'D'].includes(e.key)) {
        setIsMoving(false);
      }
    };

    // 添加事件监听
    window.addEventListener('keydown', handleKeyDown);
    window.addEventListener('keyup', handleKeyUp);

    // 清除事件监听
    return () => {
      window.removeEventListener('keydown', handleKeyDown);
      window.removeEventListener('keyup', handleKeyUp);
    };
  }, [mapWidth, mapHeight, direction]); // 添加direction依赖

  // 碰撞检测
  useEffect(() => {
    if (!characterRef.current || !availablePets || availablePets.length === 0) return;

    // 获取角色相对地图的位置
    const characterX = position.x;
    const characterY = position.y;

    // 检查与每个宠物的碰撞
    availablePets.forEach(pet => {
      const petX = pet.position.x;
      const petY = pet.position.y;
      
      // 使用地图坐标系进行碰撞检测
      if (
        characterX < petX + 40 &&
        characterX + 60 > petX &&
        characterY < petY + 40 &&
        characterY + 60 > petY
      ) {
        onCollectPet(pet.id);
      }
    });
  }, [position, availablePets, onCollectPet]);

  // 获取角色的CSS类名
  const getCharacterClass = () => {
    let className = 'character';
    className += ` facing-${direction}`;
    if (isMoving) className += ' moving';
    return className;
  };

  return (
    <div 
      ref={characterRef}
      className={getCharacterClass()}
      style={{
        left: `${position.x}px`,
        top: `${position.y}px`
      }}
    >
      <div className="character-emoji">🧑</div>
    </div>
  );
};

export default Character;